package com.zx.deploy.common.utils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@SuppressWarnings("deprecation")
public class HttpClientUtil {

	private static  Logger logger  =  Logger.getLogger(HttpClientUtil.class);
	
	/**
	 * 初始化httpClient
	 */
	private static  CloseableHttpClient httpclient = null;
	private static SSLConnectionSocketFactory sslsf = null;
	private static PoolingHttpClientConnectionManager cm = null;
    static {
        try {
        	 SSLContextBuilder builder = null;
             builder = new SSLContextBuilder();
            // 全部信任 不做身份鉴定
             builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", sslsf)
                    .build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(200);//max connection
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	
	/**
	 * 创建连接
	 */
	private static void openHttpClient(){
		 CloseableHttpClient httpClient = HttpClients.custom()
	                .setSSLSocketFactory(sslsf)
	                .setConnectionManager(cm)
	                .setConnectionManagerShared(true)
	                .build();
	        httpclient=httpClient;
	}
	
	/**
	 * 关闭连接
	 * @throws IOException 
	 */
	public static void closeHttpClient() throws IOException {
		if(httpclient!=null) {
			httpclient.close();
		}
	}
	
	/**
	 * 上传文件
	 * @param upload_url 上传文件地址
	 * @param package_path 打包文件地址
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static JSONObject upload(String upload_url,String package_path) throws ClientProtocolException, IOException { 
			   if(httpclient==null) {
				  openHttpClient();
			   }
	           HttpPost httppost = new HttpPost(upload_url); 
	           RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
	           httppost.setConfig(requestConfig);
	           FileBody bin = new FileBody(new File(package_path)); 
	           StringBody comment = new StringBody("This is comment", ContentType.TEXT_PLAIN); 
	           HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("comment", comment).build(); 
	           httppost.setEntity(reqEntity); 
	           CloseableHttpResponse response = httpclient.execute(httppost); 
	           HttpEntity resEntity = response.getEntity(); 
	           String content ="";
	           if (resEntity != null) { 
	        	   content = EntityUtils.toString(response.getEntity());
	               logger.info("httpClient.upload==>"+content);
	           } 
	           EntityUtils.consume(resEntity); 
	           response.close(); 
	           return JSON.parseObject(content); 
	   }
	
	
	/**
	 * 发送普通的post请求
	 * @param post_url
	 * @param mapParams
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws Exception
	 */
	public static JSONObject post(String post_url,Map<String,String> mapParams) throws ClientProtocolException, IOException {
		if(httpclient==null) {
			  openHttpClient();
		}
	    CloseableHttpResponse httpResponse = null;
	    HttpPost httpPost = new HttpPost(post_url);
	    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(22000).build();
	    httpPost.setConfig(requestConfig);
	    List<NameValuePair> params = new ArrayList<NameValuePair>();
	    if(mapParams!=null&&!mapParams.isEmpty()) {
	    	for (String key : mapParams.keySet()) {
	    		params.add(new BasicNameValuePair(key, mapParams.get(key)));
			}
	    }
	    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,Charset.forName("UTF-8"));
	    httpPost.setEntity(entity);
	    httpResponse = httpclient.execute(httpPost);
	    HttpEntity responseEntity = httpResponse.getEntity();
	    String content ="";
	    if(responseEntity!=null){
	        content = EntityUtils.toString(responseEntity,"UTF-8");
	        logger.info("httpClient.post==>"+content);
	    }
	    if(httpResponse!=null){
	        httpResponse.close();
	    }
	    return JSON.parseObject(content); 
	}
	
	
	/**
	 * 发送普通的login登录请求
	 * @param post_url
	 * @param mapParams
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws Exception
	 */
	public static JSONObject login(String login_url,String loginid,String psd) throws ClientProtocolException, IOException{
		if(httpclient==null) {
			  openHttpClient();
		}
	    CloseableHttpResponse httpResponse = null;
	    HttpPost httpPost = new HttpPost(login_url);
	    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(22000).build();
	    httpPost.setConfig(requestConfig);
	    List<NameValuePair> params = new ArrayList<NameValuePair>();
	    params.add(new BasicNameValuePair("loginid",loginid));
	    params.add(new BasicNameValuePair("psd",psd));
	    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,Charset.forName("UTF-8"));
	    httpPost.setEntity(entity);
	    httpResponse = httpclient.execute(httpPost);
	    HttpEntity responseEntity = httpResponse.getEntity();
	    String content="";
	    if(responseEntity!=null){
	        content = EntityUtils.toString(responseEntity,"UTF-8");
	        logger.info("httpClient.login==>"+content);
	    }
	    if(httpResponse!=null){
	        httpResponse.close();
	    }
	    return JSON.parseObject(content); 
	}
	
	
	/**
	 * 发送get请求
	 * @param log
	 * @param url
	 * @return
	 * @throws ClientProtocolException 
	 * @throws GeneralSecurityException
	 * @throws IOException
	 */
	public static  JSONObject sendGetRequest(String url) throws ClientProtocolException, IOException {	
		if(httpclient==null) {
			  openHttpClient();
		}
		logger.info("====get请求地址===="+url);
		HttpGet httpGet = new HttpGet(url);
	    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(22000).build();
	    httpGet.setConfig(requestConfig);
	    CloseableHttpResponse httpResponse = null;
	    httpResponse = httpclient.execute(httpGet);  
	    HttpEntity responseEntity = httpResponse.getEntity();
	    String resStr="";
	    if(responseEntity!=null){
	    	 resStr= EntityUtils.toString(responseEntity,"UTF-8");
	    	 logger.info("====返回结果===="+resStr);
	    }
	    if(httpResponse!=null){
	    	 httpResponse.close();
	    }
	    return JSON.parseObject(resStr); 
	}
}
